#include "socketE.h"


using namespace lvpublisher;


Socket::Socket()
{

}

Socket::Socket(const string & ip, uint16_t port)
{
    setAddr(ip, port);
}

Socket::~Socket()
{
    if(m_fd != -1)
    {
        closeSocket(m_fd);
    }
}

void Socket::setAddr(const string & ip, uint16_t port)
{
    memset(&m_addr, 0, sizeof(m_addr));
    m_addr.sin_family = AF_INET;
    m_addr.sin_addr.s_addr = inet_addr(ip.c_str());  
    m_addr.sin_port = htons(port); 
}

void Socket::createSocketfd()
{
    m_fd = socket(AF_INET, SOCK_STREAM, 0);
    // info("socket %d", m_fd);
}

void Socket::bindAddr()
{
    if(m_fd == -1) return;
    int ret = bind(m_fd, (struct sockaddr*)&m_addr, sizeof(m_addr));
    // info("bind %d", ret);
}

void Socket::listenPort()
{
    if(m_fd == -1) return;
    int ret = listen(m_fd, 1024);
    // info("listen %d", ret);

}

void Socket::setNoBlock(int fd, bool value)
{
    int flags = fcntl(fd,F_GETFL,0);
    if(value == true)
    {
        flags |= O_NONBLOCK;
    }
    else
    {
        flags &= ~O_NONBLOCK;
    }
    fcntl(fd,F_SETFL,flags);
}

int Socket::getfd()
{
    return m_fd;
}

void Socket::closeSocket(int & fd)
{
    if(fd == -1) return;
    close(fd);
    fd = -1;
}

int Socket::acceptClient()
{
    if(m_fd == -1) return -1;
    return accept(m_fd, NULL, NULL);
}

void Socket::setPortReuse()
{
    int opt = 1;
    // sockfd为需要端口复用的套接字 
    setsockopt(m_fd, SOL_SOCKET, SO_REUSEADDR, (const void *)&opt, sizeof(opt));
}
